#include "Database.h"
Database::Database()
{
     dataLocationPath = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
     dataLocationDir.setPath(dataLocationPath);
     db = QSqlDatabase::addDatabase( "QSQLITE" );
}
QStringList Database::GetDatabaseList()
{
    if(dataLocationDir.exists())
    {
        dataLocationDir.setNameFilters(QStringList("*.db"));
        QStringList databaseList = dataLocationDir.entryList();
        return databaseList;
    }
    else
    {
        qDebug("Directory does not exist.");
        return QStringList();
    }
}

void Database::CreateDatabase(QString account)
{
    QString dbFileName = dataLocationDir.path() + "/" + account + ".db";
    if(dataLocationDir.exists())
    {
        if(!QFile::exists(dbFileName))
        {
            if(OpenDatabase(account))
            {
                if(CreateTable(account))
                    qDebug("Created table");
                else
                    qDebug("Fail to create table");
            }
            else
                qDebug("Could not open database");
        }
        else
            qDebug("Database exists");

    }
    else
    {
        if(dataLocationDir.mkpath(dataLocationDir.path()))
        {
            if(OpenDatabase(account))
            {
                if(CreateTable(account))
                    qDebug("Created table");
                else
                    qDebug("Fail to create table");
            }
            else
                qDebug("Could not open database");
        }
        else
            qDebug("Fail to create directory.");

    }
}

bool Database::DeleteDatabase(QString account)
{
    QString dbName = dataLocationDir.path() + "/" + account + ".db";
    if(QFile::remove(dbName))
        return true;
    else
        return false;
}

bool Database::OpenDatabase(QString database)
{
    QString dbFileName = dataLocationDir.path()  + "/" + database + ".db";
    db.setDatabaseName(dbFileName);
    return db.open();
}

void Database::DisconnectDatabase()
{
    db.close();
}

bool Database::CreateTable(QString database)
{
    bool success = false;
    if(db.isOpen())
    {
        QSqlQuery query;
        success = query.exec("CREATE TABLE IF NOT EXISTS mail (id INTEGER UNIQUE PRIMARY KEY, email_contact VARCHAR(30), title TEXT, attachment TEXT, date VARCHAR(30))")
                && query.exec("CREATE TABLE IF NOT EXISTS contact (id INTEGER UNIQUE PRIMARY KEY, name VARCHAR(30), email VARCHAR(30))");
    }
    else
        return false;

    DisconnectDatabase();
    return success;
}


bool Database::InsertRecordToTable(QString record)
{
    return true;
}

QString Database::SelectRecordOfTable(QString nameTable, QString query)
{
    return QString();
}

bool Database::DeleteRecordOfTable(QString record)
{
    return true;
}

